package cn.wenhe9.gulimall.sms.service.impl;

import cn.wenhe9.common.utils.ResultResponse;
import cn.wenhe9.gulimall.sms.service.SmsService;
import cn.wenhe9.gulimall.sms.utils.ConstantSmsPropertiesUtils;
import cn.wenhe9.gulimall.sms.utils.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.zhenzi.sms.ZhenziSmsClient;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.bcel.Const;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author DuJinliang
 * 2022/4/14
 */
@Service
public class SmsServiceImpl implements SmsService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void send(String phone) {
        if (StringUtils.isEmpty(phone)){
            throw new RuntimeException("手机号不能为空");
        }

        ZhenziSmsClient client = new ZhenziSmsClient(ConstantSmsPropertiesUtils.API_URL, ConstantSmsPropertiesUtils.APP_ID, ConstantSmsPropertiesUtils.APP_SECRET);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("number", phone);
        params.put("templateId", ConstantSmsPropertiesUtils.TEMPLATE_ID);
        String[] templateParams = new String[2];
        String fourBitCode = RandomUtil.getFourBitRandom();
        redisTemplate.opsForValue().set(phone, fourBitCode);
        templateParams[0] = fourBitCode;
        templateParams[1] = ConstantSmsPropertiesUtils.TIMEOUT + "分钟";
        params.put("templateParams", templateParams);
        String result = null;
        try {
            result = client.send(params);
            JSONObject jsonObject = JSONObject.parseObject(result);
            Integer code = (Integer) jsonObject.get("code");
            if (code != 0){
                throw new RuntimeException("短信发送失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }
}
